const simpleServer = require('../simple-server')
const path = require('path')
const fs = require('fs')
const server = simpleServer(3000, path.join(__dirname, 'resources'))
const getFileName = require('./get-filename')
const tmp = require('./tmp')
var express = require('express')
var router = express.Router()
var multiparty = require('multiparty')
const merge = require('./merge')
const clear = require('./clear')

if (!fs.existsSync(tmp)) {
  fs.mkdirSync(tmp)
}

router.get('/merge', async function (req, res, next) {
  let chunkCount = +req.query.chunkCount
  let filename = req.query.fileName
  let file = await merge(chunkCount, filename)
  clear(chunkCount, filename)
  let date = new Date()
  // 加个后缀
  let extend = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}-${date.getMilliseconds()}`
  let renamed = file.split('.')
  let ext = renamed.pop()
  renamed.push(extend, ext)
  fs.renameSync(file, renamed.join('.'))
  res.end('good')
})

router.post('/upload', function (req, res, next) {
  //生成multiparty对象，并配置上传目标路径
  var form = new multiparty.Form({ uploadDir: tmp })
  form.parse(req, function (err, fields, files) {
    if (err) {
      console.log(err)
    } else {
      let filename = getFileName(fields.fileName[0])
      let dirPath = path.join(tmp, filename)
      if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath)
      fs.renameSync(files.chunk[0].path, path.join(dirPath, fields.chunkIndex[0]))
      res.json('haha')
    }
  })
})
server.use(router)
